package engine.newUi
{
	import engine.control.MenuList;
	import engine.data.ModelLocator;
	import engine.flag.GameDefine;
	import engine.logic.ActSee;
	import engine.logic.ChatFilterLogic;
	import engine.net.datatype.WString;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.ui.AlertUI;
	import engine.ui.MainLogic;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.tab.NxTabEvent;
	import newx.com.control.table.NxTableEvent;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;
	import newx.utils.ArrayUtils;
	
	public class MailLogic
	{
		private static var _self		:MailLogic;
		private var _ui				:MailUI;
		private var _dataList			:Array = [];
		private var _model				:ModelLocator;
		
		private var selectItems		:Array = [];
		
		/**
		 *	收件0，还是发件箱 1
		 */
		private var _index				:int;
		
		private var _curePage			:int = 1;
		
		private var _maxPage			:int = 1;
		
		private var _tempPage			:int = 1;
		
		//选择图标
		private var _selectImg:String =   "<img src='"+ SwfLoader.CDN +"res/jianxiao_ui_gouxuan_up.png' hspace = '15' vspace = '-3' />              ";
		//选中图标
		private var _selectedImg:String = "<img src='"+ SwfLoader.CDN +"res/jianxiao_ui_gouxuan_down.png' hspace = '15' vspace = '-3' />              ";
		
		//收件箱界面时的标题
		private var  ReceiveLabelArray:Array;	
		//发件箱界面时的标题
		private var  sendLabelArray:Array;
		//是否全部选中
		private var  isSelect:Boolean;
		public static function getInstance():MailLogic
		{
			if(_self == null)
			{
				_self	=	new MailLogic();
				
			}
			return _self
		}
		public function MailLogic()
		{
		}
		public function Init():void
		{
			_ui =MailUI.getInstance();
			initTab();
			
			_ui.windowBG			.addEventListener(NxWindowEvent		.WINDOW_CLOSE		,onClickClose);
			_ui.tab					.addEventListener(NxTabEvent		.TAB_CLICK			,onTabButtonClick);
			_ui.btnEmailSelectAll	.addEventListener(MouseEvent		.CLICK					,selectAll);
			_ui.btnEmailDelSelect	.addEventListener(MouseEvent		.CLICK				,delectSelect);
			_ui.btnEmailWrite		.addEventListener(MouseEvent		.CLICK				,openWrite);
			_ui.table				.addEventListener(NxTableEvent		.TABLE_CLICK		,seeMail);
			
			_ui.btnPre.addEventListener(MouseEvent.CLICK,changePage);
			_ui.btnNext.addEventListener(MouseEvent.CLICK,changePage);
			
			_model = ModelLocator.getInstance();
			
			//删除邮件成功
			_model.addEventListener(String(CustomToClientFlag.
				SERVER_CUSTOMMSG_DEL_LETTER_SUCCESS), successDelMail);
			
			//收取邮件了
			_model.addEventListener(String(CustomToClientFlag.
				SERVER_CUSTOMMSG_LETTER_GIFT_GET_RESULT),chargeMailAnnex);
			
			_ui.table.dragLineLock = [0,1,2,3];
			ReceiveLabelArray		=	[StaticIni.getSwfLangStr("TaskComUI_Choose"),
				StaticIni.getSwfLangStr("UIStr_1000442"),
				StaticIni.getSwfLangStr("Common_Email_Sender"),
				StaticIni.getSwfLangStr("Common_Email_ReceiveTime"),
				StaticIni.getSwfLangStr("Common_Attach")];
			sendLabelArray			=	[StaticIni.getSwfLangStr("TaskComUI_Choose"),
				StaticIni.getSwfLangStr("UIStr_1000442"),
				StaticIni.getSwfLangStr("Common_Email_Receiver"),
				StaticIni.getSwfLangStr("Common_Email_SendTime"),
				StaticIni.getSwfLangStr("Common_Attach")];
			_model.addEventListener(String(CustomToClientFlag.
				SERVER_CUSTOMMSG_SEND_LETTER),getMail);
		}
		
		private function initTab():void
		{
			_ui.tab.clearItems();
			
			_ui.tab.addItem(StaticIni.getSwfLangStr("Common_EmailIn"));
			_ui.tab.addItem(StaticIni.getSwfLangStr("Common_EmailOut"));
		}
		
		/**
		 *	成功删除邮件
		 */
		private function successDelMail(e:CustomMsgEvent):void
		{
			_ui.tab.selectTabByIndex(e.pList[0]);
			showMailBackList(e.pList[0]);
		}
		
		/**
		 *	查看邮件 
		 */
		private function seeMail(e:NxTableEvent):void
		{
			//找到N行的数据
			var mail:Object = getMailList(e.pos.row);
			
			//点击选在列return
			if(e.pos.colum == 0){
				changeSelect(mail,e.pos.row + _ui.table.currentPage * _ui.table.pageLinesConut);
				return;
			}
			
			if(mail == null)return;
			var menuItemList:Array = [];
			menuItemList.push(StaticIni.getSwfLangStr("Common_EmailRead_Title"));
			MenuList.ShowMenu(menuItemList,onFuncClick,mail);
		}
		
		/**
		 * 改变选择状态
		 */
		private function changeSelect(mail:Object,row:int):void
		{
			if(mail == null)return;
			if(_index == 0){
				_ui.table.setLineByIndex(resolveReceiveMail(!saveSeletedMail(mail),mail as Array),row,mail);
			}else{
				_ui.table.setLineByIndex(resolveSendMail(!saveSeletedMail(mail),mail as Array,mail[0]),row,mail);
			}
		}
		
		private function onFuncClick(index:uint,mail:Object=null):void
		{	
			if(0 == index){
				if(_index == 0){
					SeeMailLogic.getInstance().seeMail(mail);
				}else{
					SeeMailLogic.getInstance().seeSendMail(mail);
				}
			}
		}
		
		private function onTabButtonClick(e:NxTabEvent):void
		{
			isSelect=false;
			_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("Common_EmailSelectAll");//全部选择
			_index = (e == null) ? 0 : e.item.index;
			
			if(_index == 0)
			{
				_ui.table.titleLabels	=	ReceiveLabelArray;		
			}
			else
			{
				_ui.table.titleLabels	=	sendLabelArray;
			}
			selectItems = [];
			
			_ui.table.currentPage = 0;
			
			showMailBackList(_index);
		}
		
		/**
		 * 根据导航，刷新对应的邮件
		 */
		public function showMailBackList(index:int):void
		{
			var changePageOper : int = getChangePageOper(_curePage, _tempPage);
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GET_LETTERS, index, changePageOper);
		}
		
		/**
		 * 	获得操作方式  0:打开,1:向前,2:向后,3:预留
		 
		 */
		private function getChangePageOper(curePage : int, tempPage : int) : int
		{
			if(tempPage > curePage) return 2;
			if(tempPage < curePage) return 1;
			return 0;
		}
		
		/**
		 * 收取附件
		 */
		private function chargeMailAnnex(e:CustomMsgEvent):void
		{
			//收件箱会改变
			var mailId:String = e.pList[0];
			var annex:int = e.pList[1];
			//还有附件不处理
			if(annex == 1){
				return;
			}
			if(_index == 0){
				//伪造邮件
				var newMail:Array = [];
				newMail[3] = mailId;
				var mail : Object = findMail(newMail);
				if(mail[0] != -1){
					//改成已读
					mail[1][7] = "";
					_ui.table.setLineByIndex(resolveReceiveMail(false,mail[1]),mail[0],mail[1]);
				}
			}
		}
		
		/**
		 * 已读邮件
		 */
		public function readedMail(readMail : Array):void
		{
			//已读邮件，直接返回
			if(readMail[11] == 1) return;
			//收件箱会改变
			if(_index == 0){
				var row : int = findMail(readMail)[0];
				if(row != -1){
					//改成已读
					readMail[11] = 1;
					_ui.table.setLineByIndex(resolveReceiveMail(false,readMail),row,readMail);
				}
			}
		}
		
		/**
		 * 找到对应的邮件的(index,mail)
		 */
		private function findMail(readMail : Array):Array
		{
			var mail:Object;
			var leng:int = _ui.table.dataProvider.length;
			for(var i:int = 0; i < leng; i++){
				mail = _ui.table.getLineByIndex(i)[0]["data"];
				if(mail[3] == readMail[3]){
					return [i,mail];
				}
			}
			return [-1,null];
		}
		
		private function getMail(e : CustomMsgEvent) : void
		{
			MainLogic.getInstance().stopGlow(RightTopIndexUI.getInstance().bt2);
			var pList : Array = e.pList;
			var mailType : int = pList.shift();
			curePage = pList.shift();
			maxPage = pList.shift();
			var myPattern:RegExp = new RegExp(" ","g");  
			
			if(pList.length != 0 && mailType ==0)
			{
				for(var i:int = 2;i<pList.length;i+=12)
				{
					pList[i] = (pList[i].split(myPattern) as Array)[0];
				}
				
			}
			var mailList : Array = clentMailList(mailType, pList);
			
			//table.titleLabels	=	ReceiveLabelArray;
			//收信箱
			if(mailType ==0){
				receiveMail(mailList);
			}else{
				sendMail(mailList);
			}
		}
		
		
		/**
		 *	解析成客户端邮件 
		 * @param mialList
		 * @return 
		 * 
		 */
		private function clentMailList(mailType : int, mailList : Array) : Array
		{
			var mailLeng : int = mailType == 0 ? 12 : 5;
			var leng : int = mailList.length / mailLeng;
			
			var tempMailList : Array = [];
			for(var i : int = 0; i < leng; i++){
				tempMailList.push(mailList.splice(0,mailLeng));
			}
			return tempMailList;
		}
		
		/**
		 * 收信箱 
		 */
		private function receiveMail(mailList : Array):void
		{
			//所有邮件
			var tList:Array	=	mailList;
			//邮件数量
			var leng:uint	=	tList.length;
			//清空邮件
			_ui.table.dataProvider	=	null;
			
			for(var i:int = 0; i < leng; i ++)
			{
				//放入table
				_ui.table.addLineByIndex(resolveReceiveMail(false,tList[i]),-1,tList[i])
			}
		}
		
		/**
		 * 解析收件箱邮件
		 */
		private function resolveReceiveMail(select : Boolean, mail : Array):Array
		{
			//邮件颜色
			var mailColor:String;
			//是否已读
			var read:int = mail[11];
			//邮件类型
			var mailType:int = mail[4];
			
			//普通邮件颜色
			if(mailType == GameDefine.Letter_Type_Common){
				mailColor = (read == 1)?"#a1d5fd":"#1eff00";
			}else{
				mailColor = (read == 1)?"#a1d5fd":"#ff8000";
			}
			var img : String = select ? _selectedImg : _selectImg; 
			img = setColor(mailColor,img);
			//收件人
			var addressee:String;
			//标题
			var title:String;
			//时间
			var date:String;
			//是否有附件
			var annex:String;
			
			var filter : ChatFilterLogic = ChatFilterLogic.getInstance();
			
			if(mailType == GameDefine.Letter_Type_Common){//普通邮件(玩家发送的)
				title = setColor(mailColor, filter.filter(mail[5]));
				addressee = setColor(mailColor,mail[0]);
			}else if(mailType == GameDefine.Letter_Type_SysTemAuto){//带参数的系统聊天#分隔
				title = setColor(mailColor,getTip(mail[5]));
				addressee = setColor(mailColor,getTip(mail[0]));
			}else{
				title = setColor(mailColor,StaticIni.getSwfLangStr(mail[5]));
				addressee = setColor(mailColor,StaticIni.getSwfLangStr(mail[0]));
			}
			date = setColor(mailColor,mail[2]);
			annex = setColor(mailColor,StaticIni.getSwfLangStr((mail[7] == "")?"Common_Null":"UIStr_1000445"));
			return [img, title, addressee, date, annex];
		}
		
		/**
		 *	设置颜色 
		 * @param color
		 * @param content
		 * @return 
		 * 
		 */
		private function setColor(color:String,content:String):String
		{
			return "<font color='" + color + "'>" + content + "</font>" ;
		}
		
		/**
		 * 获得需要显示的提示信息 
		 * 
		 */ 
		private function getTip(pList:String):String
		{
			var tArr:Array = [];
			var trueVal		:Array = pList.split("#");
			var tSize:uint	=	trueVal.length;
			
			for(var j:uint	= 1 ; j < tSize ; j ++)
			{
				tArr.push(StaticIni.getSwfLangStr(trueVal[j]));
			}
			
			return StaticIni.getSwfLangStrVar(trueVal[0],tArr);
		}
		
		/**
		 * 发信箱
		 */
		private function sendMail( mailList : Array):void
		{
			var tList:Array	=	mailList;
			var tSize:uint	=	tList.length;		
			_ui.table	.dataProvider	=	null;
			
			for(var i:int = 0; i < tSize; i ++)
			{
				//发件箱里面收件人名字
				var addressee:String	=	tList[i][0];
				_ui.table.addLineByIndex(resolveSendMail(false,tList[i],addressee),-1,tList[i])
			}
		}
		
		/**
		 * 解析发件箱邮件
		 */
		private function resolveSendMail(select : Boolean, mail : Array, name : String):Array
		{
			var mailColor:String = "#989CA1";
			
			var img : String = select ? _selectedImg : _selectImg; 
			img = setColor(mailColor,img);
			
			//收件人
			var addressee:String;
			//标题
			var title:String;
			//时间
			var date:String;
			//是否有附件
			var annex:String;
			
			var filter : ChatFilterLogic = ChatFilterLogic.getInstance();
			
			title = setColor(mailColor, filter.filter(mail[2]));
			addressee = setColor(mailColor,name);
			date = setColor(mailColor,mail[1].substr(1,10));
			annex =  setColor(mailColor,StaticIni.getSwfLangStr("Common_Null"));
			
			return [img,title,addressee,date,annex];
		}
		
		/**
		 * 保存选中的邮件
		 */
		private function saveSeletedMail(mail:Object): Boolean
		{
			for each(var seletedMail : Array in selectItems)
			{
				if(_index == 0 && seletedMail[3] == mail[3]){
					ArrayUtils.DeleteItem(selectItems,mail);
					return true;
				}else if(_index == 1 && seletedMail[1] == mail[1]){
					ArrayUtils.DeleteItem(selectItems,mail);
					return true;
				}
			}
			selectItems.push(mail);
			return false;
		}
		
		/**
		 * 全部选中
		 */
		private function selectAll(evt : MouseEvent):void
		{
			selectItems = [];
			var mail:Object;
			var leng:int = _ui.table.pageLinesConut;
			isSelect?_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("PickUp_5"):_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("Common_EmailSelectAll");
			for(var i:int = 0; i < leng; i++)
			{
				mail = getMailList(i);
				if(mail == null) continue;
				if(_index == 0)
				{
					_ui.table.setLineByIndex(resolveReceiveMail(!isSelect,mail as Array),i + _ui.table.pageLinesConut * _ui.table.currentPage,mail);
				}
				else
				{
					_ui.table.setLineByIndex(resolveSendMail(!isSelect,mail as Array,mail[0]),i + _ui.table.pageLinesConut * _ui.table.currentPage,mail);
				}
				if(!isSelect)
				{
					selectItems.push(mail);
				}
				
			}
			if(!isSelect)
			{
				if(selectItems.length ==0) return;
			}
			
			isSelect=!isSelect;
			isSelect?_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("PickUp_5"):_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("Common_EmailSelectAll");
		}
		
		/**
		 * 删除邮件
		 */
		private function delectSelect(e:*):void
		{
			var count	:uint	=	selectItems.length;
			var pList	:Array	=	[];
			
			pList.push(count);
			var isHave:Boolean=false; //是否有附件
			for(var i:uint = 0 ; i < count ; i ++)
			{
				if(_index == 0){
					pList.push(selectItems[i][3]);
					if(selectItems[i][7]!="")
					{
						isHave=true;
					}
				}else{
					pList.push(new WString(String(selectItems[i][1])));
				}
			}
			selectItems.length	=	0;
			
			if(_index == 0){
				if(isHave)
				{
					AlertUI.showAlert("",StaticIni.getSwfLangStr("UIString_1000605"),AlertUI.YES|AlertUI.NO,clickBack,pList);
				}
				else
				{
					SystemSender.getInstance().CustomMsgEx(CustomToServerFlag.CLIENT_CUSTOMMSG_DEL_LETTERS,pList);
				}
			}else{
				SystemSender.getInstance().CustomMsgEx(CustomToServerFlag.CLIENT_CUSTOMMSG_DEL_SEND_LETTERSL,pList);
			}
		}
		private function clickBack(type:int,str:String,clickData:*):void
		{
			if(AlertUI.YES == type)//同意
			{
				SystemSender.getInstance().CustomMsgEx(CustomToServerFlag.CLIENT_CUSTOMMSG_DEL_LETTERS,clickData);
			}
		}
		
		/**
		 *	写邮件
		 */
		private function openWrite(e:*):void
		{
			SendMailUI.getInstance().showOrHide();
			_ui.hide();
		}
		
		/**
		 * 关闭
		 */
		private function onClickClose(e:*):void
		{
			_ui.hide();			
		}
		
		/**
		 * 翻页
		 */
		private function changePage(e:Event):void{
			if(e.target == _ui.btnPre){
				_tempPage = _curePage - 1;
			}else{
				_tempPage = _curePage + 1;
			}
			showMailBackList(_index);
		}
		
		/**
		 * 维护翻页按钮
		 */
		private function shwoPageBtn():void
		{
			if(_maxPage < _curePage) _maxPage = _curePage;
			
			_ui.txtPage.htmlStr = _curePage +"/"+ _maxPage;
			
			_ui.btnPre.enabled = true;
			_ui.btnNext.enabled = true;
			if(_curePage >= _maxPage){
				_ui.btnNext.enabled = false;
			}
			if(_curePage <= 1){
				_ui.btnPre.enabled = false;
			}
		}
		
		public function	AfterHide():void
		{	
			//			onTabButtonClick(null);
		}
		
		public function BeforeShow():void
		{		
			isSelect = false;
			_ui.btnEmailSelectAll.label = StaticIni.getSwfLangStr("Common_EmailSelectAll");
			ActSee.PostClientStatus(8010,1,0);	
			_ui.tab.selectTabByIndex(0);
			onTabButtonClick(null);
		}
		
		/**
		 *	获得自己的名字
		 */
		private function getMyName():String
		{
			return _model.scene.Role.GetPropertiesEx("Name");
		}
		
		private function getMailList(row : int):Object
		{
			var mail:Object = _ui.table.getLineByIndex(row + _ui.table.currentPage * _ui.table.pageLinesConut);
			if(mail == null) return null;
			return mail[0]["data"];
		}
		
		/**
		 * 	当前页码
		 */
		public function set curePage(value:int):void
		{
			_curePage = value;
			
			_tempPage = _curePage;
			
			shwoPageBtn();
		}
		
		/**
		 * 	最大页码
		 */
		public function set maxPage(value:int):void
		{
			_maxPage = value;
			
			shwoPageBtn();
		}
	}
}